<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="senior">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
        <template scope="scope">
          <span @dblclick="getEmployees(scope.$index, scope.row)" v-html="scope.row.name"></span>
        </template>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" :formatter="formatSex" sortable>
        <template scope="scope">
          <span style="color: blue" v-if="scope.row.state==1">启动</span>
          <span style="color: #ff4d51" v-else-if="scope.row.state==0">禁用</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'dept:deleteById'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增或者编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启动</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employee"
                :key="item.id"
                :label="item.username"
                :value="item">
              <!--
              value代表要传给后端的对象
              label代表页面显示的数据
              -->
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <div class="block">

            <el-cascader v-model="editForm.parent"
                :options="deparTree"
                :props="{ checkStrictly: true,
                value:'id',
                label:'name',
                }"
                clearable></el-cascader>
          </div>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

    <!--员工新增和编辑界面-->
    <el-dialog :title="title" :visible.sync="empEditFormVisible" :close-on-click-modal="false">
      <el-form :model="empEditForm" label-width="80px" :rules="empEditFormRules" ref="editForm">
        <el-form-item label="员工姓名" prop="username">
          <el-input v-model="empEditForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="empEditForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮件" prop="email">
          <el-input v-model="empEditForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工盐值" prop="salt">
          <el-input v-model="empEditForm.salt" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="empEditForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age">
          <el-input v-model="empEditForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工状态" prop="state">
          <el-input v-model="empEditForm.state" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="选择部门">
          <el-select v-model="empEditForm.department" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in dapt"
                :key="item.id"
                :label="item.name"
                :value="item">
              <!--
              value代表要传给后端的对象
              label代表页面显示的数据
              -->
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录信息">
          <el-select v-model="empEditForm.logininfo" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in logininfo"
                :key="item.id"
                :label="item.username"
                :value="item">
              <!--
              value代表要传给后端的对象
              label代表页面显示的数据
              -->
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺" prop="shop_id">
          <el-input v-model="empEditForm.shop_id" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="empEditFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="empEditSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--抽屉表格-->
    <el-drawer
        title="我嵌套了表格!"
        :visible.sync="table"
        direction="rtl"
        size="50%">
        <!--列表-->
        <el-table :data="gridData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" width="60">
          </el-table-column>
          <el-table-column prop="username" label="员工姓名" width="120" sortable>
          </el-table-column>
          <el-table-column prop="phone" label="员工电话" width="120" sortable>
          </el-table-column>
          <el-table-column prop="email" label="邮件" width="100" sortable>
          </el-table-column>
          <el-table-column prop="salt" label="盐值" width="120" sortable>
          </el-table-column>
          <el-table-column prop="password" width="200" label="密码" min-width="180" sortable>
          </el-table-column>
          <el-table-column prop="age" width="100" label="年龄" min-width="100" sortable>
          </el-table-column>
          <el-table-column prop="state" label="员工状态" width="100" :formatter="formatSex" sortable>
            <template scope="scope">
              <span style="color: #13ce66" v-if="scope.row.state==1">工作中</span>
              <span style="color: #1F2D3D" v-else-if="scope.row.state==0">休息中</span>
              <span v-else>带薪休假</span>
            </template>
          </el-table-column>
          <el-table-column prop="department.name" width="150" label="员工所属部门" min-width="180" sortable>
          </el-table-column>
          <el-table-column prop="logininfo.username" width="120" label="登录信息" min-width="180" sortable>
          </el-table-column>
          <el-table-column prop="shop_id" label="管理员" width="100" :formatter="formatSex" sortable>
            <template scope="scope">
              <span style="color: blue" v-if="scope.row.shop_id==null">平台管理员</span>
              <span style="color: #ff4d51" v-else-if="scope.row.shop_id!=null">店铺管理员</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <!--      <el-table-column prop="shop.name" width="120" label="店铺" min-width="180" sortable>-->
          <!--      </el-table-column>-->

          <el-table-column label="操作" width="150">
            <template slot="header" slot-scope="scope">
              <el-button type="success" size="small" @click="empHandleAdd(scope.$index, scope.row)">
                新增
              </el-button>
            </template>
            <template scope="scope">
              <el-button size="small" @click="empHandleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="emphandleDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
          <el-button type="danger" @click="empBatchRemove" :disabled="this.sels.length===0">批量删除</el-button>
          <el-pagination layout="prev, pager, next" @current-change="empHandleCurrentChange" :page-size="pageSizes" :current-page="currentPages" :total="totals" style="float:right;">
          </el-pagination>
        </el-col>
    </el-drawer>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
          keyword:''
				},
				departments: [],
				total: 0,
				pageSize: 5,
        currentPage:1,
        title:"",
        // 员工页码，总条数和每页显示条数
        totals: 0,
        pageSizes: 5,
        currentPages:1,
        titles:"",
        employee:[],
        deparTree:[],
        dapt:[],
        logininfo:[],

				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
        empEditFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          sn: [
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					]
				},
        empEditFormRules: {
          username: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ]
        },
        table: false,
        dialog: false,
        loading: false,
        gridData: [],

				//编辑界面数据
				editForm: {
          id:null,
          sn:"",
          name:"",
          state:1,
          manager:null,
          parent:null,
				},
        //员工编辑界面数据
        empEditForm: {
          id:null,
          username:'',
          phone:'',
          email:'',
          salt:'',
          password:'',
          age:null,
          state:null,
          department_id:null,
          logininfo_id:null,
          shop_id:null,
          department:null,
          shop:null,
          logininfo:null,
        },


			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
      // 员工根据页面查询数据
      empHandleCurrentChange(val) {
        this.currentPages = val;
        this.emphandleDel()
      },
			//获取用户列表
			getDepartments() {
				let para = {
				  // 模糊查询
          keyword: this.filters.keyword,
          // 当前显示条数
					pageSize: this.pageSize,
          // 当前页数
					currentPage: this.currentPage
				};
				this.listLoading = true;
				// 发起axios请求
        this.$http.post("/dept",para).then(result=>{
          // 将后端获取的数据赋值给页面
          this.departments = result.data.rows
          // 将总条数赋值给页面
          this.total = result.data.total
          console.log(result.data.total)
          // 关闭忙等
          this.listLoading = false;
        })

			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/dept/"+row.id).then(result=>{
					  // 关闭忙等
            this.listLoading = false;
            // 修改页码为第一页
            this.currentPage = 1;
            if (result.data.success){
              this.$message({
                message: result.data.message,
                type: 'success'
              });
            // 调用查询方法
            this.getDepartments()
            }else {
              this.$message({
                message: result.data.message,
                type: 'success'
              });
            }
          }).catch(result=>{
            // 关闭忙等
            this.listLoading = false;
            // 修改页码为第一页
            this.currentPage = 1;
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.title = "修改",
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
				// 获取row的dirPath在通过/进行分割
        let arr = row.dirPath.split("/")
        // 创建一个新的数组
        let arrays = [];
				// 这里的1是去除第一个数字，后面的减1是去除最后一个数字
        for (let i = 1;i < arr.length - 1;i++){
          // 将转为int类型的数据放进新的数组里面
          arrays.push(parseInt(arr[i]));
        }
        // 最后设置进去
        this.editForm.parent = arrays;
			},
      //员工显示编辑界面
      empHandleEdit: function (index, row) {
        this.title = "修改",
            this.empEditFormVisible = true;
        this.empEditForm = Object.assign({}, row);
        console.log(this.empEditForm)
        console.log("-----")
      },
			//显示新增界面
			handleAdd: function () {
			  this.title = "新增";
				this.editFormVisible = true;
				this.editForm = {
          id:null,
          sn:"",
          name:"",
          state:1,
          manager:null,
          parent:null
				};
			},
      //显示员工新增和修改界面
      empHandleAdd: function () {
        this.title = "新增"
        this.empEditFormVisible = true;
        this.empEditForm = {
          id:null,
          username:'',
          phone:'',
          email:'',
          salt:'',
          password:'',
          age:null,
          state:null,
          department_id:null,
          logininfo_id:null,
          shop_id:null,
          department:null,
          shop:null,
          logininfo:null,
        };
      },
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
              // 先判断部门是否为null
              if (para.parent!=null){
                // 获取并且回显上级部门
                para.parent = {"id": para.parent[para.parent.length-1]}
              }
              // 发起请求
              this.$http.put("/dept",para)
                  .then(result=>{
                    // 关闭按钮忙等
                    this.editLoading = false;
                    // 关闭模态框
                    this.editFormVisible = false;
                    // 修改页码为第一页
                    this.currentPage = 1;
                    if (result.data.success){
                      this.$message({
                        message: result.data.message,
                        type: 'success'
                      });
                      // 调用查询方法
                      this.getDepartments()
                    }else {
                      this.$message({
                        message: result.data.message,
                        type: 'success'
                      });
                    }
                  }).catch(result=>{
                // 关闭按钮忙等
                this.editLoading = false;
                // 修改页码为第一页
                this.currentPage = 1;
                this.$message({
                  message: "系统繁忙",
                  type: 'error'
                });
              })
						});
					}
				});
			},
      //员工新增和编辑
      empEditSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              //NProgress.start();
              // 获取的数据改为员工表
              let para = Object.assign({}, this.empEditForm);
              // 发起axios请求
              this.$http.put("/employee",para)
                  .then(result=>{
                    // 关闭按钮忙等
                    this.editLoading = false;
                    // 关闭模态框
                    this.empEditFormVisible = false;
                    // 修改页码为第一页
                    this.currentPage = 1;
                    // 关闭抽屉表格
                    this.table = false;
                    if (result.data.success){
                      this.$message({
                        message: result.data.message,
                        type: 'success'
                      });
                    }else {
                      this.$message({
                        message: result.data.message,
                        type: 'success'
                      });
                    }
                    // 调用查询方法
                    this.getDepartments()
                  }).catch(result=>{
                // 关闭忙等
                this.editLoading = false;
                // 修改页码为第一页
                this.currentPage = 1;
                this.$message({
                  message: "系统繁忙",
                  type: 'error'
                });
              })


            });
          }
        });
      },
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/dept",ids).then(result=>{
            // 关闭忙等
            this.listLoading = false;
            // 修改页码为第一页
            this.currentPage = 1;
            if (result.data.success){
              this.$message({
                message: result.data.message,
                type: 'success'
              });
              // 调用查询方法
              this.getDepartments()
            }else {
              this.$message({
                message: result.data.message,
                type: 'success'
              });
            }
          }).catch(result=>{
            // 关闭忙等
            this.listLoading = false;
            // 修改页码为第一页
            this.currentPage = 1;
            this.$message({
              message: "系统繁忙",
              type: 'error'
            });
          })
        })
				.catch(() => {

				});
			},
      //批量删除
      empBatchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          // 发起请求
          this.$http.patch("/employee",ids).then(result=>{
            // 关闭忙等
            this.listLoading = false;
            // 修改页码为第一页
            this.currentPage = 1;
            // 关闭抽屉表格
            this.table = false;
            if (result.data.success){
              this.$message({
                message: result.data.message,
                type: 'success'
              });
            }else {
              this.$message({
                message: result.data.message,
                type: 'success'
              });
            }
            // 调用查询方法
            this.getDepartments()
          }).catch(result=>{
            // 关闭忙等
            this.listLoading = false;
            // 修改页码为第一页
            this.currentPage = 1;
            this.$message({
              message: "系统繁忙",
              type: 'error'
            });
          })
        })
            .catch(() => {

            });
      },

      senior(){
        this.currentPage = 1
        this.getDepartments();
      },
      // 查询所有员工
      getEmployee(){
        this.$http.get("/employee")
            .then(result=>{
              this.employee = result.data
            }).catch(result=>{

        })
      },
      // 获取部门树数据
      getTree(){
			  this.$http.get("/dept/findtree")
        .then(result=>{
          this.deparTree = result.data;
        }).catch(Result=>{

        })
      },
      //获取抽屉员工列表
      getEmployees(index, row) {
        let para = {
          pageSizes: this.pageSizes,
          currentPages: this.currentPages,
          // 模糊查询
          keyword: this.filters.keyword,
        };
        this.listLoading = true;
        // 发送axios请求获取员工数据
        this.$http.get("/employee/findempById/"+row.id)
            .then(result=>{
              // 关闭忙等
              this.listLoading = false;
              // 将员工数据赋值给页面
              this.gridData = result.data;
              // 赋值总条数
              // this.total = result.data;
              // console.log(result.data.total)
            }).catch(result=>{

        })
        this.table = true;

      },
      // //根据id删除抽屉员工
      emphandleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          // 发起删除请求
          this.$http.delete("/employee/"+row.id).then(result=>{
            // 关闭忙等
            this.listLoading = false;
            // 将页面改为第一页
            this.currentPages = 1;
            // 刷新部门页面
            this.getDepartments()
            // 关闭抽屉框
            this.table = false;

            // 判断是否为true
            if(result.data.success){
              this.$message({
                message: result.data.message,
                type: 'success'})
            }else {
              this.$message({
                message: result.data.message,
                type: 'success'})
            }
          }).catch(result=>{
            this.$message({
              message: "系统繁忙",
              type: 'error'})
          })
        }).catch(() => {

        });
      }
    ,
    // 查询所有部门
    dapts(){
      this.$http.get("/dept")
          .then(result=>{
            this.dapt = result.data
          }).catch(result=>{

      })
    },
    // 查询所有登录数据
    getLogininfo(){
      this.$http.get("/logininfo")
          .then(result=>{
            this.logininfo = result.data
            console.log("-----")
            console.log(result.data)
          }).catch(result=>{

      })
    },

		},
		mounted() {
		  // 查询所有员工
			this.getDepartments();
			// 查询新增模态框的下拉框数据
			this.getEmployee();
			// 查询部门树
			this.getTree();
      // 调用查询所有部门
      this.dapts();
      // 查询登录信息
      this.getLogininfo();
		}
	}

</script>

<style scoped>

</style>